<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="message-container">
                <div class="message-header">
                    <h2>我的消息</h2>
                </div>
                
                <div class="message-list" v-if="chats.length > 0">
                    <div v-for="chat in chats" :key="chat.id" 
                         class="message-item" 
                         @click="goToChat(chat)">
                        <el-image
                            style="width: 50px; height: 50px; border-radius: 50%;"
                            :src="getChatUserAvatar(chat)"
                            fit="cover">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-user-solid"></i>
                            </div>
                        </el-image>
                        <div class="message-info">
                            <div class="message-user">
                                <span class="nickname">{{getChatUserName(chat)}}</span>
                                <span class="time">{{formatTime(chat.lastMessageTime)}}</span>
                            </div>
                            <div class="message-preview">
                                {{getLastMessage(chat)}}
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="empty-message" v-else>
                    <i class="el-icon-chat-dot-round"></i>
                    <p>暂无聊天记录</p>
                </div>
            </div>
        </app-body>
    </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue';

export default {
    name: "message",
    components: {
        AppHead,
        AppBody
    },
    data() {
        return {
            chats: [],
            currentUser: JSON.parse(localStorage.getItem('userInfo') || '{}'),
            chatUsers: {},
            refreshTimer: null
        };
    },
    created() {
        // 检查是否登录
        const token = localStorage.getItem('token');
        if (!token) {
            this.$message.warning('请先登录');
            this.$router.push('/login');
            return;
        }

        this.loadChats();
        
        // 设置定时刷新
        this.refreshTimer = setInterval(() => {
            this.loadChats();
        }, 5000);
    },
    beforeDestroy() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
        }
    },
    methods: {
        loadChats() {
            this.$api.getUserChats().then(res => {
                if (res.code === 200) {
                    this.chats = res.data;
                    // 预加载所有聊天对象的用户信息
                    this.chats.forEach(chat => {
                        // 根据当前用户ID和聊天信息判断对方用户ID
                        let otherUserId;
                        if (Number(this.currentUser.userId) === Number(chat.buyerId)) {
                            // 如果当前用户是买家，显示卖家信息
                            otherUserId = chat.sellerId;
                        } else if (Number(this.currentUser.userId) === Number(chat.sellerId)) {
                            // 如果当前用户是卖家，显示买家信息
                            otherUserId = chat.buyerId;
                        }
                        
                        if (otherUserId) {
                            // 立即加载用户信息
                            this.loadChatUserInfo(chat, otherUserId);
                        }
                    });
                } else {
                    this.$message.error(res.message || '加载聊天列表失败');
                }
            }).catch(err => {
                console.error('加载聊天列表失败:', err);
                this.$message.error('网络错误，请稍后重试');
            });
        },
        loadChatUserInfo(chat, otherUserId) {
            // 从服务器获取用户信息
            this.$api.getUserDetail(otherUserId).then(res => {
                if (res.code === 200 && res.data) {
                    const userInfo = {
                        id: otherUserId,
                        nickname: res.data.nickname || res.data.userName || '未知用户',
                        avatarUrl: res.data.avatarUrl || ''
                    };
                    // 使用Vue的响应式更新
                    this.$set(chat, 'otherUser', userInfo);
                } else {
                    console.error('加载用户信息失败:', res.message);
                    this.$set(chat, 'otherUser', {
                        id: otherUserId,
                        nickname: '未知用户',
                        avatarUrl: ''
                    });
                }
            }).catch(err => {
                console.error('加载用户信息失败:', err);
                this.$set(chat, 'otherUser', {
                    id: otherUserId,
                    nickname: '未知用户',
                    avatarUrl: ''
                });
            });
        },
        getChatUserName(chat) {
            if (!chat.otherUser) {
                // 根据当前用户ID和聊天信息判断对方用户ID
                let otherUserId;
                if (Number(this.currentUser.userId) === Number(chat.buyerId)) {
                    otherUserId = chat.sellerId;
                } else if (Number(this.currentUser.userId) === Number(chat.sellerId)) {
                    otherUserId = chat.buyerId;
                }
                
                if (otherUserId) {
                    // 直接返回对方用户ID，让模板显示ID
                    return `用户${otherUserId}`;
                }
                return '未知用户';
            }
            return chat.otherUser.nickname;
        },
        getChatUserAvatar(chat) {
            if (!chat.otherUser) {
                return '';
            }
            return chat.otherUser.avatarUrl;
        },
        getLastMessage(chat) {
            if (!chat.lastMessage) return '';
            const isCurrentUser = Number(chat.lastMessageSenderId) === Number(this.currentUser.userId);
            const otherUserNickname = chat.otherUser ? chat.otherUser.nickname : '对方';
            return isCurrentUser ? `我: ${chat.lastMessage}` : `${otherUserNickname}: ${chat.lastMessage}`;
        },
        formatTime(time) {
            if (!time) return '';
            const date = new Date(time);
            const now = new Date();
            const diff = now - date;
            
            // 今天的消息只显示时间
            if (diff < 24 * 60 * 60 * 1000) {
                return date.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
            }
            
            // 昨天的消息显示"昨天"
            if (diff < 48 * 60 * 60 * 1000) {
                return '昨天';
            }
            
            // 一周内的消息显示星期几
            if (diff < 7 * 24 * 60 * 60 * 1000) {
                const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                return '星期' + weekdays[date.getDay()];
            }
            
            // 更早的消息显示具体日期
            return date.toLocaleDateString('zh-CN', {
                month: '2-digit',
                day: '2-digit'
            });
        },
        goToChat(chat) {
            if (!chat.id || !chat.sellerId || !chat.buyerId) {
                this.$message.error('聊天参数错误');
                return;
            }
            this.$router.push({
                path: '/chat',
                query: {
                    chatId: chat.id,
                    sellerId: chat.sellerId,
                    buyerId: chat.buyerId,
                    productId: chat.productId
                }
            });
        }
    }
};
</script>

<style scoped>
.message-container {
    min-height: calc(100vh - 120px);
    background-color: #f5f5f5;
    padding: 20px;
}

.message-header {
    background-color: #fff;
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message-header h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
}

.message-list {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message-item {
    display: flex;
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s;
}

.message-item:hover {
    background-color: #f9f9f9;
}

.message-item:last-child {
    border-bottom: none;
}

.message-info {
    flex: 1;
    margin-left: 15px;
    overflow: hidden;
}

.message-user {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.nickname {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.time {
    font-size: 12px;
    color: #999;
}

.message-preview {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.empty-message {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: #999;
}

.empty-message i {
    font-size: 48px;
    margin-bottom: 15px;
}

.empty-message p {
    font-size: 16px;
    margin: 0;
}
</style>